package com.atguigu.realtime.app.dwd.db;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.bean.TableProcess;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.FlinkSinkUtil;
import com.atguigu.realtime.util.JdbcUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Connection;
import java.util.*;

/**
 * @Author lzc
 * @Date 2023/3/15 11:00
 */
@Slf4j
public class Dwd_08_DwdBaseDb extends BaseApp {
    public static void main(String[] args) {
        new Dwd_08_DwdBaseDb().init(
            4008,
            2,
            "Dwd_08_DwdBaseDb",
            Constant.TOPIC_ODS_DB
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        
        SingleOutputStreamOperator<TableProcess> tpStream = readTableProcess(env);
        
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> dataTpStream = connect(etledStream, tpStream);
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> resultStream = delNotNeedColumns(dataTpStream);
        
        writeToKafka(resultStream);
        
        
    }
    
    private void writeToKafka(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getKafkaSink());
    }
    
    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> delNotNeedColumns(
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> dataTpStream) {
        return dataTpStream
            .map(new MapFunction<Tuple2<JSONObject, TableProcess>, Tuple2<JSONObject, TableProcess>>() {
                @Override
                public Tuple2<JSONObject, TableProcess> map(Tuple2<JSONObject, TableProcess> t) throws Exception {
                    
                    // 根据 sink 字段删除 数据中的不需要的字段
                    //"aa,c"
                    List<String> columns = Arrays.asList(t.f1.getSinkColumns().split(","));
                    
                    // data中的 key是否存在于集合columns中, 如果存在就保留, 不存在就删除
                    JSONObject data = t.f0;
                    Set<String> keys = data.keySet();
                    keys.removeIf(key -> !columns.contains(key) && !"op_type".equals(key));
                    return t;
                }
            });
    }
    
    
    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> connect(
        SingleOutputStreamOperator<JSONObject> dataStream,
        SingleOutputStreamOperator<TableProcess> tpStream) {
        // 1. 把配置流做成广播流
        // key: "表名+":" +ALL"
        // value: TableProcess
        MapStateDescriptor<String, TableProcess> tpStateDesc = new MapStateDescriptor<>("tpState", String.class, TableProcess.class);
        BroadcastStream<TableProcess> tpBcStream = tpStream.broadcast(tpStateDesc);
        // 2. 数据流去 connect 广播流
        return dataStream
            .connect(tpBcStream)
            .process(new BroadcastProcessFunction<JSONObject, TableProcess, Tuple2<JSONObject, TableProcess>>() {
                
                private HashMap<String, TableProcess> map;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 预加载配置信息
                    // 1. 获取 jdbc 连接
                    Connection conn = JdbcUtil.getMysqlConnection();
                    // 2. 查询配置表中所有数据(执行查询语句)  执行一个查询语句, 把结果封装起来
                    String sql = "select * from gmall_config.table_process";
                    List<TableProcess> list = JdbcUtil.queryList(conn, sql, null, TableProcess.class, true);
    
                    for (TableProcess tp : list) {
                        System.out.println("预加载数据: " + tp);
                    }
                    // 3. 把查到的结果存入到 Map中
                    map = new HashMap<>();
                    for (TableProcess tp : list) {
                        if ("dwd".equals(tp.getSinkType())) { // 只需要 dwd 的配置信息
                            String key = getKey(tp.getSourceTable(), tp.getSourceType(), tp.getSinkExtend() == null ? "" : tp.getSinkExtend());
                            map.put(key, tp);
                        }
                    }
                    // 4. 关闭连接
                    conn.close();
                    
                }
                
                // 4. 读取数据流的数据, 从广播状态中读取配置信息
                @Override
                public void processElement(JSONObject obj,
                                           ReadOnlyContext ctx,
                                           Collector<Tuple2<JSONObject, TableProcess>> out) throws Exception {
                    
                    ReadOnlyBroadcastState<String, TableProcess> state = ctx.getBroadcastState(tpStateDesc);
                    
                    // 针对优惠券下单和优惠券支付进行特殊处理
                    String table = obj.getString("table");
                    String type = obj.getString("type");
                    String sinkExtends = "";
                    if ("coupon_use".equals(table) && "update".equals(type)) {
                        JSONObject old = obj.getJSONObject("old");
                        JSONObject data = obj.getJSONObject("data");
                        
                        if ("1401".equals(old.getString("coupon_status")) && "1402".equals(data.getString("coupon_status"))) {
                            // 优惠券下单
                            sinkExtends = "{\"data\": {\"coupon_status\": \"1402\"}, \"old\": {\"coupon_status\": \"1401\"}}";
                        } else if ("1402".equals(old.getString("coupon_status")) && "1403".equals(data.getString("coupon_status"))) {
                            sinkExtends = "{\"data\": {\"used_time\": \"not null\"}}";
                        }
                    }
                    String key = getKey(table, type, sinkExtends);
                    
                    TableProcess tp = state.get(key);
                    if (tp == null) {
                        System.out.println(key + " 在广播状态中 没有找  到配置");
                        // 从 map 读取
                        tp = map.get(key);
    
                        if (tp == null) {
                            System.out.println(key + " 在Map中 也没有 找到配置");
                        }else{
                            System.out.println(key + " 在Map中 找到 配置");
        
                        }
                    }else{
                        System.out.println(key + " 在广播状态中  找到  配置");
                    }
                    
                    // 如果tp是 null,表示这条数据不是想要的维度数据
                    if (tp != null) {
                        JSONObject data = obj.getJSONObject("data");
                        data.put("op_type", obj.getString("type"));
                        out.collect(Tuple2.of(data, tp));
                    }
                }
                
                // 3. 读取广播流中的数据, 把配置信息放入到广播状态
                // 每来一条数据, 有几个并行度, 就不执行几次
                @Override
                public void processBroadcastElement(TableProcess tp,
                                                    Context ctx,
                                                    Collector<Tuple2<JSONObject, TableProcess>> out) throws Exception {
                    System.out.println(tp);
                    
                    // 1. 获取广播状态
                    BroadcastState<String, TableProcess> state = ctx.getBroadcastState(tpStateDesc);
                    // 2. 把配置存入到状态中
                    String key = getKey(tp.getSourceTable(), tp.getSourceType(), tp.getSinkExtend() == null ? "" : tp.getSinkExtend());
                    
                    if ("d".equals(tp.getOp())) {
                        // 如果这次的配置是删除, 则需要删除状态中的配置信息
                        state.remove(key);
                        // map 中配置也要删
                        map.remove(key);
                        
                    } else { // c r u
                        state.put(key, tp);
                    }
                    
                }
                
                private String getKey(String table, String type, String sinkExtends) {
                    return table + ":" + type + ":" + sinkExtends;
                }
                
            });
        
        
    }
    
    private SingleOutputStreamOperator<TableProcess> readTableProcess(StreamExecutionEnvironment env) {
        // url?useSSL=false
        Properties props = new Properties();
        props.setProperty("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname(Constant.MYSQL_HOST)
            .port(Constant.MYSQL_PORT)
            .databaseList("gmall_config") // set captured database, If you need to synchronize the whole database, Please set tableList to ".*".
            .tableList("gmall_config.table_process") // set captured table
            .username("root")
            .password("aaaaaa")
            .jdbcProperties(props)
            .deserializer(new JsonDebeziumDeserializationSchema()) // converts SourceRecord to JSON String
            .startupOptions(StartupOptions.initial()) // 启动时候读取快照(表内所有数据), 然后监控 binlog,读取最新的数据
            .build();
        
        return env
            .fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql-cdc")
            .map(new MapFunction<String, TableProcess>() {
                @Override
                public TableProcess map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    String op = obj.getString("op");
                    TableProcess tp;
                    if ("d".equals(op)) {
                        tp = obj.getObject("before", TableProcess.class);
                    } else {
                        tp = obj.getObject("after", TableProcess.class);
                    }
                    tp.setOp(op);
                    return tp;
                }
            })
            .filter(tp -> "dwd".equals(tp.getSinkType())); // 过滤出事实表的配置信息
        
        
    }
    
    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        
        
        return stream
            .filter(new FilterFunction<String>() {
                @Override
                public boolean filter(String value) throws Exception {
                    try {
                        JSONObject obj = JSON.parseObject(value);
                        String type = obj.getString("type");
                        String data = obj.getString("data");
                        return "gmall2022".equals(obj.getString("database"))
                            && null != obj.getString("table")
                            && ("insert".equals(type)
                            || "update".equals(type)
                            || "delete".equals(type)
                            || "bootstrap-insert".equals(type))
                            && null != data
                            && data.length() > 2;
                    } catch (Exception e) {
                        //System.out.println("数据格式不对,不是正确的 json 数据: " + value);
                        log.warn("数据格式不对,不是正确的 json 数据: " + value);
                        return false;
                    }
                }
            })
            .map(json -> JSON.parseObject(json.replaceAll("bootstrap-", "")));
        
    }
    
    
}
